﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Jayden.Dll.Cards.Drawing
{
	public class ChipsImage
	{
		private int m_Depth;
		private int m_WidthCount;
		private int m_HeightCount;
		private ulong[] m_Value;
		private Image m_Images;
		private Image[] m_Image;

		private Size m_ChipSize;

		public ChipsImage(string filename, int depth, int widthCount, int heightCount, params ulong[] values)
		{
			m_Depth = depth;
			m_Images = Image.FromFile(filename);
			m_WidthCount = widthCount;
			m_HeightCount = heightCount;
			m_Value = values;
			m_Image = new Image[widthCount * heightCount];
			m_ChipSize = new Size(m_Images.Width / widthCount, m_Images.Height / heightCount);
		}

		public int Depth { get { return m_Depth; } }
		public int Width { get { return m_ChipSize.Width; } }
		public int Height { get { return m_ChipSize.Height; } }
		
		public Image GetImage(int index)
		{
			return GetImage(index % m_WidthCount, index / m_WidthCount);
		}
		public Image GetImage(int x, int y)
		{
			int index = x + y * m_WidthCount;
			Image image = m_Image[index];
			if (image == null)
			{
				image = new Bitmap(m_ChipSize.Width, m_ChipSize.Height);
				using (Graphics g = Graphics.FromImage(image))
				{
					g.DrawImage(m_Images, 0, 0, new Rectangle(x * m_ChipSize.Width, y * m_ChipSize.Height, m_ChipSize.Width, m_ChipSize.Height), GraphicsUnit.Pixel);
				}
				m_Image[index] = image;
			}
			return image;
		}

		public ulong GetValue(int x, int y)
		{
			int index = x + y * m_WidthCount;
			if(index >= m_Value.Length)
				return 0;
			return m_Value[index];
		}
		public ulong GetValue(int index) { return m_Value[index]; }

		public List<int> GetIndexes(ulong amount)
		{
			List<int> results = new List<int>();
			for (int c = m_Value.Length - 1; amount > 0 && c >= 0; c--)
			{
				ulong value = m_Value[c];
				while (amount >= value)
				{
					results.Add(c);
					amount -= value;
				}
			}
			return results;
		}
	}
}
